package logic

import (
	"context"
	"fmt"
	"library/models/cache"
	"library/models/mysql"

	"library/libraryrpc/internal/svc"
	"library/libraryrpc/libraryrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserLoginLogic) UserLogin(in *libraryrpc.UserLoginRequest) (*libraryrpc.UserLoginResponse, error) {
	// todo: add your logic here and delete this line
	get := cache.RedisDB.Get(l.ctx, "sendSms"+in.Mobile)
	if get.Val() != in.SmsCode {
		return nil, fmt.Errorf("短信验证码错误,请重新输入")
	}
	var users mysql.User
	mysql.DB.Where("mobile=?", in.Mobile).Find(&users)
	if users.ID == 0 {
		return nil, fmt.Errorf("用户名错误,请重新输入")
	}
	return &libraryrpc.UserLoginResponse{
		UserId: int64(users.ID),
	}, nil
}
